package com.lvyuely.web.module.auth;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.lvyuely.web.module.entity.auth.Account;
import com.lvyuely.web.module.service.auth.AccountService;

public class AuthRealm extends AuthorizingRealm {

	private final static Logger logger = Logger.getLogger(AuthRealm.class);

	@Autowired
	private AccountService accountService;

	/**
	 * 访问权限控制
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		try {
			String username = (String) principals.fromRealm(getName()).iterator().next();
			logger.info("username aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[" + username + "]");
			if (StringUtils.isNotEmpty(username)) {
				logger.info("username[" + username + "]");
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				info.addStringPermission("/index");
				info.addStringPermission("/api");
				return info;
			}
		} catch (Throwable t) {
			logger.error("", t);
		}
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 用户登录控制
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
		// TODO Auto-generated method stub
		UsernamePasswordToken token = (UsernamePasswordToken) authToken;
		String username = token.getUsername();
		String password = new String(token.getPassword());
		logger.info("username[" + username + "] password[" + password + "]");
		if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
			// 验证登录
			Account account = accountService.login(new Account(username, password));
			if (account != null) {
				logger.info("auth success");
				return new SimpleAuthenticationInfo(account.getUsername(), account.getPassword(), getName());
			}
		}
		return null;
	}
}
